package tuanda.soict.firstsun.PresentationPackage;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.tiled.TileAtlas;
import com.badlogic.gdx.graphics.g2d.tiled.TileMapRenderer;
import com.badlogic.gdx.graphics.g2d.tiled.TiledLoader;
import com.badlogic.gdx.graphics.g2d.tiled.TiledMap;
import com.badlogic.gdx.math.Vector3;

public class TiledMapHelper {
	private static final int[] layersList = { 0, 1 };
	private FileHandle packFileDirectory;
	private OrthographicCamera camera;
	private TileAtlas tileAtlas;
	private TileMapRenderer tileMapRenderer;
	private TiledMap map;
	private int mapWidth, mapHeight, width, height;
	private Vector3 tmp;

	public TiledMapHelper() {
		tmp = new Vector3(0, 0, 0);
	}

	public void create() {
		width = Gdx.graphics.getWidth();
		height = Gdx.graphics.getHeight();
	}

	public void render() {
		tileMapRenderer.getProjectionMatrix().set(camera.combined);
		tmp.set(0, 0, 0);
		camera.unproject(tmp);
		tileMapRenderer.render((int) tmp.x, (int) tmp.y, width, height,
				layersList);

	}

	public int getHeight() {
		return mapHeight;
	}

	public int getWidth() {
		return mapWidth;
	}

	public TiledMap getMap() {
		return map;
	}

	public TileMapRenderer getTileMapRenderer() {
		return this.tileMapRenderer;
	}

	public void dispose() {
		tileAtlas.dispose();
		tileMapRenderer.dispose();
	}

	public void setPackerDirectory(String packDirectory) {
		packFileDirectory = Gdx.files.internal(packDirectory);
	}

	public void loadMap(String tmxFile) {
		if (packFileDirectory == null) {
			throw new IllegalStateException("loadMap() called out of sequence");
		}
		map = TiledLoader.createMap(Gdx.files.internal(tmxFile));
		tileAtlas = new TileAtlas(map, packFileDirectory);
		tileMapRenderer = new TileMapRenderer(map, tileAtlas, 10, 10);
		mapWidth = map.width * map.tileWidth;
		mapHeight = map.height * map.tileHeight;
	}

	public void prepareCamera(int screenWidth, int screenHeight) {
		camera = new OrthographicCamera(screenWidth, screenHeight);
		camera.position.set(0, mapWidth, 0);
	}

	public OrthographicCamera getCamera() {
		if (camera == null) {
			throw new IllegalStateException(
					"getCamera() called out of sequence");
		}
		return camera;
	}

}
